import tkinter as tk
from tkinter import ttk 
from tkinter import messagebox 
from db import db

import re
class CreateFrame(tk.Frame):
    def __init__(self,root):
        super().__init__(root)
        
        self.archive_id=tk.StringVar(value=db.archive_id())
        self.name=tk.StringVar()
        self.unit=tk.StringVar()
        self.person_id=tk.StringVar()
        self.age=tk.StringVar()
        self.gender=tk.StringVar()
        self.phone_number=tk.StringVar()
        self.mail=tk.StringVar()
        self.mailname = tk.StringVar() 
        self.domain = tk.StringVar()
        

        self.status=tk.StringVar()
        self.create_page()
    def submit(self):
           
        self.mail.set(f"{self.mailname.get()}{self.domain.get()}")
           
        
        
        if not all(var.get().strip() for var in [self.name, self.unit, self.person_id, self.phone_number, self.gender, self.mailname, self.domain]):
            messagebox.showerror("错误", "所有字段必须填写,请检查并填写")
            return
        self.age.set(db.calculate_age(self.person_id.get()))
        self.recode_info()
        
            
    def create_page(self):
        tk.Label(self).grid(row=0,pady=10)
        tk.Label(self,text='姓名:').grid(row=1,column=1,pady=10)
        tk.Entry(self,textvariable=self.name).grid(row=1,column=2,pady=10)
        tk.Label(self,text='单位:').grid(row=2,column=1,pady=10)
        tk.Entry(self,textvariable=self.unit).grid(row=2,column=2,pady=10)
        tk.Label(self,text='身份证ID:').grid(row=3,column=1,pady=10)
        tk.Entry(self,textvariable=self.person_id).grid(row=3,column=2,pady=10)
        tk.Label(self,text='电话号码:').grid(row=4,column=1,pady=10)
        tk.Entry(self,textvariable=self.phone_number).grid(row=4,column=2,pady=10)
        tk.Label(self,text='性别:').grid(row=5,column=1,pady=10)
        ttk.Combobox(self,values=['男','女'],state='readonly',textvariable=self.gender,width=17).grid(row=5,column=2,pady=10)
        tk.Label(self,text='邮箱:').grid(row=6,column=1,pady=10)
        tk.Entry(self,textvariable=self.mailname).grid(row=6,column=2,pady=10)
        ttk.Combobox(self,values=['@163.com','@qq.com','@126.com','@gmail.com'],state='readonly',textvariable=self.domain,width=10).grid(row=6,column=3,pady=10)

        tk.Button(self, text="提交", command=self.submit,width=40).grid(row=7, column=2, pady=20)


    def recode_info(self):
        vlt = {
                "archive_id":self.archive_id.get(),
                "name":self.name.get(),
                "age":self.age.get(),
                "unit":self.unit.get(),
                "gender":self.gender.get(),
                "person_id":self.person_id.get(),
                "phone_number":self.phone_number.get(),
                "mail":self.mail.get()
                }
        for i in range(1,6):
            header_id = f"header_id{i}"

            vlt[header_id]=db.header_id(1)
    

        
        db.create(vlt)
        db.save()
        print(vlt)
        self.status.set('已创建该档案')

        messagebox.showinfo(title='创建成功',message=self.status.get())
        
        self.name.set('')
        self.age.set('')
        self.unit.set('')
        self.gender.set('')
        self.person_id.set('')
        self.phone_number.set('')
        self.mailname.set('')
        self.domain.set('')
class SearchFromFrame(tk.Frame):
    def __init__(self, root):
        super().__init__(root)
        self.table_view=tk.Frame
        self.table_view.pack(self)
        self.create_page()
        
    def create_page(self):
        
        columns = ("archive_id", "name", "age","unit" ,"gender", "person_id", "phone_number", "mail")
        
        columns_values = ("档案编号","姓名","年龄","单位","性别","身份证","电话号码","邮箱")
        self.tree_view = ttk.Treeview(self,show='headings',columns=columns)
        self.tree_view.column('archive_id',width=100,anchor='center')
        self.tree_view.column('name',width=60,anchor='center')
        self.tree_view.column('age',width=40,anchor='center')
        self.tree_view.column('unit',width=60,anchor='center')
        self.tree_view.column('gender',width=40,anchor='center')
        self.tree_view.column('person_id',width=120,anchor='center')
        self.tree_view.column('phone_number',width=90,anchor='center')
        self.tree_view.column('mail',width=150,anchor='center')
        
        
        self.tree_view.heading('archive_id',text='档案ID')
        self.tree_view.heading('name',text='姓名')
        self.tree_view.heading('age',text='年龄')
        self.tree_view.heading('unit',text='单位')
        self.tree_view.heading('gender',text='性别')
        self.tree_view.heading('person_id',text='身份证ID')
        self.tree_view.heading('phone_number',text='电话号码')
        self.tree_view.heading('mail',text='邮箱')
        self.tree_view.pack(fill=tk.BOTH,expand=True)
        self.show_data_frame()
        tk.Button(self,text='数据刷新',command=self.show_data_frame).pack()
    def show_data_frame(self):
        for i in self.tree_view.get_children():
            self.tree_view.delete(i)
            
            
    
        index=1
        volunteers = db.all()
        for vlt in volunteers:
            
            self.tree_view.insert('',index+1,values=(
                vlt['archive_id'],
                vlt['name'],
                vlt['age'],
                vlt['unit'],
                vlt['gender'],
                vlt['person_id'],
                vlt['phone_number'],
                vlt['mail']
            ))
class SearchHeaderIdFrame(tk.Frame):
    def __init__(self, root):
        super().__init__(root)
        

    #     self.table_view=tk.Frame
    #     self.table_view.pack(self)
        self.create_page()
    def create_page(self):
        
        tk.Label(self,text='暂未开放',font=("黑体",40),anchor="center").pack()

    #     columns = ("name", "archive_id", 'header_id1', 'header_id2', 'header_id3', 'header_id4', 'header_id5')
    #     columns_values = ('姓名', '档案编号', '表头编号1', '表头编号2', '表头编号3', '表头编号4', '表头编号5')
    #     self.tree_view = ttk.Treeview(self,show='headings',columns=columns)
    #     for col, text in zip(columns, columns_values):
    #         self.tree_view.column(col, width=100, anchor='center')
    #         self.tree_view.heading(col, text=text)
    #     self.tree_view.pack(fill=tk.BOTH, expand=True)
    #     tk.Button(self, text='数据刷新', command=self.show_data_frame).pack()
    #     self.show_data_frame()  # 初始化时显示数
    # def show_data_frame(self):
    #     # 删除所有现有项
    #     for i in self.tree_view.get_children():
    #         self.tree_view.delete(i)
        
    #     # 从数据库获取数据并插入到Treeview中
    #     volunteers = db.all()  # 确保db.all()返回正确格式的数据
    #     for vlt in volunteers:
    #         self.tree_view.insert('', 'end', values=(  # 使用'end'自动添加到最后
    #             vlt['name'],
    #             vlt['archive_id'],
    #             vlt['header_id1'],
    #             vlt['header_id2'],
    #             vlt['header_id3'],
    #             vlt['header_id4'],
    #             vlt['header_id5']
    #         ))
        





                    
class SearchEngineFrame(tk.Frame):
    def __init__(self, root):
        super().__init__(root)
        self.search_info=tk.StringVar()
        self.create_page()
    def create_page(self):
        tk.Label(self,text='搜索',font=("黑体",40)).grid(row=0,column=0,pady=20)
        tk.Label(self,text='搜索信息:',font=("黑体",20)).grid(row=1,column=0)
        tk.Entry(self,textvariable=self.search_info,width=40).grid(row=1,column=1,ipady=20)
        tk.Button(self, text="搜索", command=self.search_record,width=10).grid(row=1,column=2,padx=20,ipady=20)
    def search_record(self):
        search_text = self.search_info.get()
        
        if not search_text:
            messagebox.showwarning("警告", "请输入搜索内容")
            return
 
        search_results = db.search(search_text)  # 执行搜索
 
        if search_results:
            for result in search_results:
                self.show_result(result)
        else:
            messagebox.showwarning("警告", "未找到匹配记录")
    def show_result(self, result):
        # 格式化并展示搜索结果
        result_text = (
            f"档案编号：{result['archive_id']}\n"
            f"姓名：{result['name']}\n"
            f"单位：{result['unit']}\n"
            f"身份证：******{result['person_id'][-4:]}\n"
            f"年龄：{result['age']}\n"
            f"邮箱：{result['mail']}\n"
            f"性别：{result['gender']}\n"
            f"手机号：{result['phone_number']}\n"
        )
 
        number_pattern = re.compile(r'header_id(\d+)')   
        for key, value_list in result.items():
        
            if key.startswith("header_id"):
                
                match = number_pattern.match(key)
                if match:
                    number = match.group(1)  
                else:
                    
                    continue
                
                # 从列表中获取值（由于每个列表只有一个元素，所以直接取索引0）
                value = value_list[0]
            
                result_text += f"表头编号{number}:{value}\n"

        messagebox.showinfo("搜索结果", result_text)
        self.search_info.set('')

            
 
        




        
        
 
        
        
        
class DeleteFrame(tk.Frame):
    def __init__(self,root):
        super().__init__(root)
        
        tk.Label(self,text='delete',font=('黑体',50)).pack()
        

class ChangeFrame(tk.Frame):
    def __init__(self,root):
        super().__init__(root)
        
        tk.Label(self,text='change',font=('黑体',108)).pack()
class InsertFrameA(tk.Frame):
    def __init__(self,root):
        super().__init__(root)
        self.insertInfo=tk.StringVar()
        self.archiveId=tk.StringVar()
        self.length=tk.StringVar()
        
        


        self.create_page()
    def create_page(self):
        
        tk.Label(self,text='插 入 C S V 信 息',font=('黑体',20)).grid(row=0,column=0)
        tk.Entry(self,textvariable=self.insertInfo,width=80).grid(row=1,column=0,ipady=15)
        tk.Button(self,text='插 入 C S V ',command=self.sumbit).grid(row=1,column=1,ipady=15)
        
        
    
        
    





    def sumbit(self):
        insert_text = self.insertInfo.get()
        # 尝试解析文本
        try:
            # 假设输入文本是按行分隔的，每行是一个记录
            records = insert_text.strip().split('\n')
            # 遍历每条记录
            for record in records:
                # 分割记录为字段列表，并去除可能的空白字符
                fields = [field.strip() for field in record.split(',')]
                if len(fields) < 13:  # 根据你的字段数量要求
                    raise ValueError("记录中的字段数量不足")
                # 提取字段并创建字典
                data_dict = {
                    "archive_id": fields[0],
                    "name": fields[1],
                    "age": fields[4],  # 年龄是第五个字段
                    "unit": fields[2],
                    "gender": fields[6],
                    "person_id": fields[3],  # 身份证号码是第四个字段
                    "phone_number": fields[7],
                    "mail": fields[5],  # 邮箱是第六个字段（但按照您的示例，它在年龄之后，这里为了匹配您的示例而调整）
                    # 表头编号X~N，这里假设有5个
                    "header_id1": [fields[8]],
                    "header_id2": [fields[9]],
                    "header_id3": [fields[10]],
                    "header_id4": [fields[11]],
                    "header_id5": [fields[12]],
                }
                # 将字典添加到列表中
                db.create(data_dict)
            # 调用save方法保存数据
            db.save()
            # 显示成功消息
            messagebox.showinfo("提交成功", "数据已成功解析并保存！")
            self.insertInfo.set('')
        except Exception as e:
            # 显示错误消息
            messagebox.showerror("错误", f"解析数据时发生错误：{e}")
    
class InsertFrameB(tk.Frame):
    def __init__(self,root):
        super().__init__(root)
        self.id=tk.StringVar()
        self.length=tk.StringVar()
        self.create_page()



    def create_page(self):
        
        tk.Label(self,text='给',font=('黑体',18)).grid(row=0,column=0,pady=100)
        tk.Entry(self,textvariable=self.id,width=12,font=('黑体',18)).grid(row=0,column=1,ipady=8)
        tk.Label(self,text='插入',font=('黑体',18)).grid(row=0,column=2)
        tk.Entry(self,textvariable=self.length,width=10,font=('黑体',18)).grid(row=0,column=3,ipady=8)
        tk.Label(self,text='条表头编号',font=('黑体',18)).grid(row=0,column=4)
        tk.Button(self,text='插入',command=self.submit).grid(row=0,column=5)
    
    def submit(self):
        # archive_id = self.id.get().strip()
        # try:
        #     num_headers = int(self.length.get().strip())
        #     if num_headers <= 0:
        #         raise ValueError("数量必须为正整数")
        # except ValueError as e:
        #     messagebox.showerror("输入错误", str(e))
        #     return
 
        # volunteer = db.insert_search(archive_id)
        # if not volunteer:
        #     messagebox.showerror("错误", "未找到指定的档案编号")
        #     return
 
       
        # db.insert_update()
        # db.save()  
        messagebox.showinfo("成功", "功能缺陷")
        self.id.set('')
        self.length.set('')
        
 
    



        

        

class AboutFrame(tk.Frame):
    def __init__(self,root):
        super().__init__(root)
        
        self.create_page()
    def create_page(self):
        info_list = db.info()  # 这将是一个字典列表
        key_mapping = {
        'Version': '版本',
        'Writer': '作者',
        'Description':"描述",
        'leastUpdateTime': '最后更新日期',
        'Copyright': '版权所有',
        'OpenSourceWebsite': '开源地址',
        'MoreInfo':'更多信息',
        'CodeLanguage':'代码语言'
        }



        tk.Label(self,text='志愿者管理平台系统',font=('黑体',20)).pack(pady=20)
        
 
        # 遍历列表并创建标签
        for info_dict in info_list:
            for key, value in info_dict.items():
                # 检查键是否在映射字典中，并替换为中文键（如果需要）
                chinese_key = key_mapping.get(key, key)  # 如果key不在映射中，则保持原样
                # 创建标签，但只显示非隐藏的键（即不显示'PackName'和'exeName'）
                if key not in ['packName', 'exeName','Explain']:
                    
                    tk.Label(self, text=f"{chinese_key}: {value}",font=('黑体',16)).pack(pady=10)
                
        tk.Button(self,text='检查更新',command=self.checkUpdate).pack(pady=40,ipadx=20)
        tk.Button(self,text='说明',command=self.Explain).pack(ipadx=20)
    def checkUpdate(self):
        messagebox.showinfo("检查更新", "功能缺陷")
        pass
    def Explain(self):
        self.Explain=db.info()[0]['Explain']
        messagebox.showinfo("说明", f"主要有管理员、志愿者、档案三个模块\n{self.Explain}")

        

class RegisterFrameA(tk.Frame):
    def __init__(self,root):
        super().__init__(root)
        
        tk.Label(self,text='create5').pack()

class DeleteFrameA(tk.Frame):
    def __init__(self,root):
        super().__init__(root)
        
        tk.Label(self,text='create4').pack()
        

class ManageFrameA(tk.Frame):
    def __init__(self,root):
        super().__init__(root)
        
        tk.Label(self,text='create3').pack()
        
class ConfigFrameA(tk.Frame):
    def __init__(self,root):
        super().__init__(root)
        
        tk.Label(self,text='create2').pack()
      
class AuditFrameA(tk.Frame):
    def __init__(self,root):
        super().__init__(root)
        
        tk.Label(self,text='审核',font=('黑体',50)).pack()
class SETTINGFrame(tk.Frame):
    def __init__(self,root):
        super().__init__(root)
        self.version=db.info()[0]['Version']
        tk.Label(self,text='设置',font=('黑体',20)).pack()
        self.create_page()
    def create_page(self):
        tk.Button(self,text='Test',command=self.test).pack()
    def test(self):
        messagebox.showinfo("测试", f"当前版本为VERSION{self.version}")



































